package com.example.wuyeguanli.tools;
import android.content.Context;
import android.content.SharedPreferences;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

public class WorkOrderGenerator {

    private static final String PREFS_NAME = "WorkOrderPrefs";
    private static final String KEY_LAST_DATE = "last_date";
    private static final String KEY_LAST_SEQUENCE = "last_sequence";
    private static final Random random = new Random();

    /**
     * 生成工单号。此方法是线程安全的。
     * @param context Context对象，用于访问SharedPreferences
     * @return 生成的工单号，格式为 "yyyyMMddXXX"
     */
    public static synchronized String generate(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        // 1. 使用 Calendar 和 SimpleDateFormat 获取当前日期字符串
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        String currentDateStr = dateFormatter.format(calendar.getTime());

//        // 2. 读取上次保存的数据
//        String lastDateStr = prefs.getString(KEY_LAST_DATE, "");
//        int lastSequence = prefs.getInt(KEY_LAST_SEQUENCE, 0);
//
//        int newSequence;
//
//        // 3. 判断日期是否为同一天
//        if (currentDateStr.equals(lastDateStr)) {
//            // 同一天，序列号递增
//            newSequence = lastSequence + 1;
//        } else {
//            // 新的一天，序列号重置为 1
//            newSequence = 1;
//        }
//
//        // 4. 格式化序列号，补足3位
//        String sequenceStr = String.format(Locale.getDefault(), "%03d", newSequence);

        int randomPart = random.nextInt(900) + 100;
        // 5. 拼接工单号
        String workOrderId = currentDateStr + randomPart;

//        // 6. 将新数据保存回SharedPreferences
//        SharedPreferences.Editor editor = prefs.edit();
//        editor.putString(KEY_LAST_DATE, currentDateStr);
//        editor.putInt(KEY_LAST_SEQUENCE, newSequence);
//        editor.apply();

        return workOrderId;
    }
}
